#!/usr/bin/env python
# encoding: utf-8

 
import smtplib
import codecs
import re
import sys 
sys.path.append("../")
import scriptgoodies

def getForm(env):
	form = codecs.open(env["static"]["cwMail_template"],"r","utf8").read()
	if env["prefs"]["cwMail_passwordMasked"]: # the default password is defined in Preferences
		form = re.sub(r".+%\(cwMail_passwordMasked\)s\n","",form)
	return form

def getEmptyForm(env):
	env["prefs"]["cwMail_body"] = env["context"]["selection"]
	suffix = env["meta"]["richSuffix"]
	if suffix:
		suffixes = suffix.upper().split(" ")
		favoriteAddresses = []
		for m in re.finditer(r"\W*(.+?)\W*<(.+?)>",env["prefs"]["cwMail_favoriteCorrespondents"]):
			favoriteName = re.sub(r"(?u)\W+","",m.group(1)).upper()
			favoriteAddresses.extend("%s <%s>" % (m.group(1),m.group(2)) for s in suffixes if s == favoriteName)
		if favoriteAddresses:
			env["prefs"]["cwMail_defaultToField"] = ", ".join(favoriteAddresses)
	form = "%s(=\n%s)" % (env["meta"]["name"],getForm(env))
	text = form % env["prefs"]
	return [("replace",text),("moveCursor",text.index("(=")-len(text))]

def getFilledForm(env):
	text = env["context"]["selection"]
	form = getForm(env)
	pattern = re.sub(r"%\(\S+?\)s","(.*?)",form).replace("(.*?)(.*?)","(.*?)")
	match = re.search(pattern,text,flags=re.DOTALL)
	if not match:
		raise ValueError
	groups = match.groups()
	fields = ["From","To","Cc","Bcc","Subject","Body"]
	if env["prefs"]["cwMail_passwordMasked"] == "":
		fields.insert(1,"Password")
	if len(fields) != len(groups):
		raise ValueError
	return dict(zip(fields,groups))

def sendMail(filledForm,env):
	message = u"""Content-Type: text/plain; charset="utf-8"\nFrom: %(From)s\nTo: %(To)s\nCC: %(Cc)s\nBCC: %(Bcc)s\nSubject: %(Subject)s\n\n%(Body)s\n""".replace("\n","\r\n") % filledForm
	toAddresses = filter(None,filledForm["To"].split(",") + filledForm["Cc"].split(",") + filledForm["Bcc"].split(","))
	if env["prefs"]["cwMail_ssl"]:
		server = smtplib.SMTP_SSL(str(env["prefs"]["cwMail_smtp"]),str(env["prefs"]["cwMail_port"]))
	else:
		server = smtplib.SMTP(str(env["prefs"]["cwMail_smtp"]),str(env["prefs"]["cwMail_port"]))
	# server.set_debuglevel(1)
	user = env["prefs"]["cwMail_user"] if env["prefs"]["cwMail_user"] else filledForm["From"]
	server.login(user,env["prefs"]["cwMail_passwordMasked"] if env["prefs"]["cwMail_passwordMasked"] else filledForm["Password"])
	server.sendmail(filledForm["From"], toAddresses, message.encode("utf8"))
	server.quit()

def mayArchiveMail(filledForm,env):
	path = scriptgoodies.getArchivePath(env,env["static"]["cwMail_archiveName"])
	form = codecs.open(env["static"]["cwMail_archiveTemplate"],"r","utf8").read()
	archivedText = form % filledForm
	i = archivedText.rfind(env["prefs"]["cwMail_defaultSignature"])
	archivedText = archivedText[:i if i>0 else len(archivedText)]
	if env["prefs"]["archiveUnsaved"] != "no":
		codecs.open(path,"w","utf8").write(archivedText)
	return archivedText

def main(env):
	if env["prefs"]["cwMail_smtp"] == "" or \
	   env["prefs"]["cwMail_port"] == "" or \
	   env["prefs"]["cwMail_user"] == "":
		form = codecs.open(env["static"]["cwMail_initialTemplate"],"r","utf8").read() % env["prefs"]
		return [
			("moveCursor",0),
			("replace",form),
			("moveCursor",form.index("(=")-len(form))
		]
	try:
		filledForm = getFilledForm(env)
	except ValueError:
		return getEmptyForm(env)
	sendMail(filledForm,env)
	archivedText = mayArchiveMail(filledForm,env)
	return [
		("messageBox",env["static"]["cwMail_successMessage"]+env["static"]["cwMail_notArchivedMessage" if env["prefs"]["archiveUnsaved"] == "no" else "cwMail_archivedMessage"]),
		("replace",""),
		("remember", archivedText)
	]
